<template>
	<div style="position: relative;" class="gjhf">
		<div style="width: 100%;height: 87vh;" id="amap" class="mymap">
		</div>
		<div>
			<div :style="drawBtnStyle" @click="changeBtn">
				<i :class="drawBtnIcon" style="color: #fff;"></i>
			</div>
			<el-drawer v-if="drawer" :visible.sync="drawer" :direction="direction" :before-close="handleClose"
				:modal="false" :modal-append-to-body="false" :append-to-body="false" :style="drawStyle"
				:wrapperClosable="false" class="my-draw" :show-close="false" :withHeader="false">
				<left-container @on-selected="selectNode"></left-container>
			</el-drawer>

		</div>
		<div :style="{position: 'absolute',top: '0px',left: videoFrame.left+'vw',width: '100%','z-index':111}">
			<header-tools :nodes.sync="selectedNodes" @selected-day="selectDay" @selected-hour="selectHour" />
			<div style="display: flex;justify-content: center;margin-top: 10px;">
				<div style=" display: flex; background: #fff;align-items: center;">
					<div class="progressDiv_playBtn">
						<!-- //0->未开始  1->行驶中  2->暂停 -->
						<img v-if="carPalyStayus == 0" @click="startAnimation(lineArr)"
							src="@/assets/images/cljk/progress-play.png" width="30px" height="30px" />
						<img v-if="carPalyStayus == 1" @click="pauseAnimation"
							src="@/assets/images/cljk/progress-pause.png" width="30px" height="30px" />
						<img v-if="carPalyStayus == 2" @click="resumeAnimation"
							src="@/assets/images/cljk/progress-play.png" width="30px" height="30px" />
					</div>
					<div class="progressDiv_sliderDiv" style="width: 20vw;margin: 0 20px;">

						<el-slider v-model="sliderVal" @change="sliderChange" :show-tooltip="true"></el-slider>
					</div>
					<div class="progressDiv_speedDiv" style="width: 68px; margin-right: 10px;">
						<el-select v-model="speedCount" @change="speedCountChange($event)" placeholder="倍速选择"
							:clearable="false" size="mini">
							<el-option v-for="(item,index) in speedCountArr" :label="item.name" :value="item.value"
								:key="index" />
						</el-select>
					</div>
				</div>
			</div>
		</div>


		<div>
			<div :style="bottomdraw.btn.style" @click="changeBottom">
				<i :class="bottomdraw.btn.icon" style="color: #fff;"></i>
			</div>
			<el-drawer v-if="bottomdraw.show" :visible.sync="bottomdraw.show" :direction="bottomdraw.direction"
				:modal="false" :modal-append-to-body="false" :append-to-body="false" :style="bottomdraw.style"
				:wrapperClosable="false" class="bottom-draw" :show-close="false" :withHeader="false">
				<div style="width: 100%;display: flex;justify-content: end;">
					<i class="el-icon-full-screen" @click="changeBottomFullScreen"></i>
				</div>

				<bottom-container :nodes.sync="selectedNodes" :curDay.sync="curDate"
					:bottomHeight.sync="bottomdraw.style.height" :sourceTableData.sync="routeInfo"
					:curIndex.sync="curIndex" :curHour.sync="curHour" @load-tc="loadTc" />


			</el-drawer>

		</div>




	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import AMapLoader from '@amap/amap-jsapi-loader';
	import leftContent from './left/left-container.vue'
	import bottomContent from './bottom/bottom-container.vue'
	import headerTools from './header-tools.vue'
	import {
		getHistory
	} from '@/api/cljk.js';
	import mapCarRun from "@/assets/images/cljk/map-car-run.png";
	import coordtransform from 'coordtransform';
	import stopPoint from "@/assets/images/cljk/car-point.png";
	export default {
		components: {
			'left-container': leftContent,
			'bottom-container': bottomContent,
			'header-tools': headerTools
		},
		computed: {
			...mapState("GlobalStore", [
				"isCollapseLeftMenu",
				"globalLeftMenuTree",
			]),
		},
		watch: {
			isCollapseLeftMenu: function(val) {
				if (val) {
					if (this.drawer) {
						this.bottomdraw.style.width = '65vw'
					} else {
						this.bottomdraw.style.width = '85vw'
					}

				} else {
					if (this.drawer) {
						this.bottomdraw.style.width = '76vw'
					} else {
						this.bottomdraw.style.width = '96vw'
					}
				}
			},
			curIndex: function(val) {
				this.beforeData = this.lineArr.slice(0, val + 1); //包含val;
				this.afterData = this.lineArr.slice(val + 1); //不包含val;因为不包含所以不能设置setPostion;
				this.sliderVal = parseInt(((val + 1) / this.lineArr.length) * 100)
				if (this.beforeData.length > 0) {

					let location = new AMap.LngLat(this.lineArr[val][0], this.lineArr[val][1])
					this.carWindow.setPosition(location);
					this.setVehicleSpeedInWidowns(location)

					this.passedPolyline.setPath(this.beforeData); //设置走过的路径;
				}

				if (this.isSliderValChange) {
					this.map.remove(this.marker)
					this.marker = null
					let location = new AMap.LngLat(this.lineArr[val][0], this.lineArr[val][1])
					this.marker = new AMap.Marker({
						map: this.map,
						position: location,
						icon: new AMap.Icon({
							image: mapCarRun,
							size: new AMap.Size(22, 28), //图标所处区域大小
							imageSize: new AMap.Size(22, 28) //图标大小
						}),
						autoRotation: true,
						offset: new AMap.Pixel(-26, -13),
						angle: 0,
					});
					this.map.add(this.marker)
					var that = this
					this.marker.moveAlong(this.afterData, {
						duration: 200, //可根据实际采集时间间隔设置速度
						// JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
						autoRotation: false,
					});
					this.marker.on("moving", (e) => {
						var lastLocation = e.passedPath[e.passedPath.length - 1];
						that.carWindow.setPosition(lastLocation);
						that.map.setCenter(lastLocation, true)
						that.setVehicleSpeedInWidowns(lastLocation);
					});
					this.isSliderValChange = false
				}
			}
		},

		data() {

			return {
				speedCount: 1,
				sliderVal: 0,
				carPalyStayus: 0,
				recordePathData: [],
				speedCountArr: [{
						name: "1倍",
						value: 1
					},
					{
						name: "2倍",
						value: 2
					},
					{
						name: "3倍",
						value: 3
					}


				],
				drawer: true,
				rliShow: false,
				direction: 'ltr',
				drawStyle: {
					position: 'absolute',
					width: '20vw',
					'height': '86vh',
				},
				drawBtnIcon: 'el-icon-d-arrow-left',
				drawBtnStyle: {
					width: '30px',
					height: '30px',
					position: 'absolute',
					top: '42px',
					left: '20vw',
					'z-index': 99999,
					'text-align': 'center',
					background: 'rgba(0,0,0,0.3)',
					'border-radius': '50%',
					'align-items': 'center',
					display: 'flex',
					'justify-content': 'center'
				},

				bottomdraw: {
					show: true,
					direction: 'btt',
					style: {
						position: 'absolute',
						width: '65vw',
						height: '37vh',
						left: '21vw'
					},
					fullBtn: {
						num: 0
					},
					btn: {
						icon: 'el-icon-bottom',
						style: {
							width: '30px',
							height: '30px',
							position: 'absolute',
							bottom: '38vh',
							left: '60vw',
							'z-index': 111,
							'text-align': 'center',
							background: 'rgba(0,0,0,0.3)',
							'border-radius': '50%',
							'align-items': 'center',
							display: 'flex',
							'justify-content': 'center'
						}
					}
				},
				map: null,
				cluster: null,
				selectedNodes: null,
				infoWindow: null,
				pointers: [],
				videoFrame: {
					left: 20
				},

				curDate: null,
				marker: null,
				lineArr: [],
				progval: 1,
				progvalLength: 1,
				isSpeedCountChange: false,
				isSliderValChange: false,
				passedPolyline: null,
				polyline: null,
				afterData: [],
				beforeData: [],
				routeInfo: [],
				carWindow: null,
				curIndex: 0,
				curHour: null,
				tcData: null
			}


		},
		methods: {
			loadTc(p) {
				//加载停车数据
				this.tcData = p
			},
			sliderChange(p) {
				//手动拖动进度条过程中触发：移动车辆，定位车辆回放位置
				var that = this;
				//计算拖动进度条后车辆对应轨迹新的索引值
				var getIndex = Math.round(that.lineArr.length * that.sliderVal / 100);
				var currentIndex = 0
				if (getIndex > 0) {
					currentIndex = getIndex - 1;
				}

				var vehicleLocation = that.lineArr[currentIndex];
				if (vehicleLocation) {

					that.marker.setPosition(new AMap.LngLat(vehicleLocation[0], vehicleLocation[1]));
				}
				if (currentIndex == 0) {
					that.progval = 1; //处理重新绘制线路时 that.progval-1 找不到值报错
				} else {
					that.progval = currentIndex;
				}
				that.progvalLength = that.progval;
				// carPalyStayus //0->未开始  1->行驶中  2->暂停

				if (that.carPalyStayus == 1) {
					that.marker.stopMove(); // 先暂停车
					that.isSliderValChange = true;
					this.curIndex = currentIndex
					// this.startAnimation(this.afterData)
				} else if (that.carPalyStayus == 2) {
					that.isSliderValChange = true;
				}
			},
			resumeAnimation() {
				var that = this;
				//如果点击了暂停，并切换了倍数，从新绘制
				if ((that.carPalyStayus == 2 && that.isSpeedCountChange) || (that.carPalyStayus == 2 && that
						.isSliderValChange)) {
					that.isSpeedCountChange = false;
					that.isSliderValChange = false;
					// that.reDrawPolyline(2); //倍数变化之后，需要从新绘制线
				}
				that.marker.resumeMove();
				that.carPalyStayus = 1; //0->未开始  1->行驶中  2->暂停

			},
			pauseAnimation() {
				this.marker.pauseMove();
				this.carPalyStayus = 2; //0->未开始  1->行驶中  2->暂停
			},
			startAnimation(array) {
				var carDuration = 600 * this.speedCount
				//
				if (this.sliderVal > 0 && this.carPalyStayus == 0) { //未播放的情况下，直接从指定位置开始播放
					// this.map.setZoom(18);
					// this.reDrawPolyline(0); //倍数变化之后，需要从新绘制线
				} else { //从头开始播放
					this.carPalyStayus = 1; //0->未开始  1->行驶中  2->暂停
					var that = this;
					AMap.plugin("AMap.MoveAnimation", () => {

						that.markerSpeed = 600 * this.speedCount; //markerSpeed的值是100;
						this.marker.moveAlong(array, {
							duration: 200, //可根据实际采集时间间隔设置速度
							// JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
							autoRotation: false,
						});
						this.marker.on("moving", (e) => {
							var lastLocation = e.passedPath[e.passedPath.length - 1];
							that.carWindow.setPosition(lastLocation);
							that.map.setCenter(lastLocation, true)
							that.setVehicleSpeedInWidowns(lastLocation);
						});
					});


				}
				// carDuration：移动速度，单位：米/秒
			},

			setVehicleSpeedInWidowns(lnglat) {
				for (var i = 0; i < this.routeInfo.length; i++) {
					let content = `
								<div style="background: #000;color: #fff;padding: 8px 25px 8px 5px;font-size: 14px;">${this.routeInfo[i].cheliangpaizhao}</div>
								<div style="padding: 0 10px;line-height: 25px;font-size: 14px;">
									<div>时间：${this.routeInfo[i].gpstime}</div>
									<div>所在经度：${this.routeInfo[i].lng}</div>
									<div>所在纬度：${this.routeInfo[i].lat}</div>
									<div>速度：${this.routeInfo[i].velocity.toFixed(2)} km/h</div>
									<div>海拔：${this.routeInfo[i].elevation.toFixed(2)} </div>
									<div>行使里程：${this.routeInfo[i].distSum!==null?(this.routeInfo[i].distSum-this.routeInfo[0].distSum).toFixed(3):0} km</div>
									<div>总里程：${this.routeInfo[i].distTotal} km</div>
								</div>
							`;
					if (lnglat.distance(new AMap.LngLat(this.routeInfo[i].lng, this.routeInfo[i].lat)) < 4) {
						this.curIndex = i
						this.carWindow.setContent(content);
						return;
					}
				}
			},

			initializePaths(paths) {
				var line;
				var pathLngLatArray = new Array();
				if (paths) {
					for (var i = 0; i < paths.length; i++) {
						pathLngLatArray.push(new AMap.LngLat(paths[i].lng, paths[i].lat));
					}
					line = new AMap.Polyline({
						map: this.map,
						path: pathLngLatArray,
						strokeColor: 'red',
						strokeOpacity: 0.8,
						strokeWeight: 6,
						strokeStyle: 'solid'
					});
					line.setMap(this.map);
				}
				return line;
			},
			formatSecond(time) {
			      const h = parseInt(time / 3600)
			      const minute = parseInt(time / 60 % 60)
			      const second = Math.ceil(time % 60)    
			 
			      const hours = h < 10 ? '0' + h : h
			      const formatSecond = second > 59 ? 59 : second
			      return `${hours > 0 ? `${hours}小时` : ''}${minute < 10 ? '0' + minute : minute}分${formatSecond < 10 ? '0' + formatSecond : formatSecond}秒`
			},
			drawTc() {
				for (var i = 0; i < this.tcData.length; i++) {
					
					var flameOutStr=this.formatSecond(this.tcData[i].flameOut)
					
					var content = `<div style="height: 30px;width: 92px;color:#fff;background: orange;border-radius: 10% 20% 30% 40%;font-size: 12px;font-weight: bold;text-align: center;display: flex;justify-content: center;align-items: center;">${flameOutStr}</div><div style="height: 30px; width: 30px;"><img style="width: 100%; height: 100%" src="${stopPoint}"></img></div>`;
					
					var marker = new AMap.Marker({
					    content: content,  // 自定义点标记覆盖物内容
					    position:  [this.tcData[i].lng, this.tcData[i].lat], // 基点位置
					});
					
					this.map.add(marker);
					
					
					
				}
				
			},

			selectHour(p) {
				this.curHour = p
				if (this.curDate && this.selectedNodes) {
					getHistory({
						startTime: this.curDate + ' ' + this.curHour.startHour,
						endTime: this.curDate + ' ' + this.curHour.endHour,
						vehId: this.selectedNodes.id
					}).then(res => {
						if (res.code === 200) {
							this.map.clearMap();
							if (this.tcData) {
								this.drawTc()
							}
							this.routeInfo = res.data
							if (this.routeInfo.length === 0) {
								this.$message({
									message: '该时段无数据',
									type: 'warning'
								});
								return
							}
							this.marker = new AMap.Marker({
								map: this.map,
								position: [this.routeInfo[0].lng, this.routeInfo[0].lat],
								icon: new AMap.Icon({
									image: mapCarRun,
									size: new AMap.Size(22, 28), //图标所处区域大小
									imageSize: new AMap.Size(22, 28) //图标大小
								}),
								autoRotation: true,
								offset: new AMap.Pixel(-26, -13),
								angle: 0,
							});
							this.map.add(this.marker)

							this.carWindow = new AMap.InfoWindow({
								offset: new AMap.Pixel(6, -25),
								content: ""
							});

							var pathPolyline = this.initializePaths(this.routeInfo);
							this.lineArr = []

							for (var i = 0; i < res.data.length; i++) {
								var lng = res.data[i].lng
								var lat = res.data[i].lat

								this.lineArr.push(
									[lng, lat]
								)
							}

							this.passedPolyline = new AMap.Polyline({
								map: this.map,
								path: this.lineArr,
								strokeColor: "#AF5", //线颜色
								strokeOpacity: 1, //线透明度
								strokeWeight: 6, //线宽
								strokeStyle: "solid" //线样式
							});

							this.map.add(this.passedPolyline)

							// 7.打开速度框
							this.carWindow.open(this.map, this.marker.getPosition());

							this.map.setFitView();



						}
					})
				}
			},
			selectDay(p) {
				this.curDate = p

				if (this.selectedNodes && this.curHour) {
					getHistory({
						startTime: p + ' ' + this.curHour.startHour,
						endTime: p + ' ' + this.curHour.endHour,
						vehId: this.selectedNodes.id
					}).then(res => {
						if (res.code === 200) {
							this.map.clearMap();
							if (this.tcData) {
								this.drawTc()
							}
							this.routeInfo = res.data

							this.marker = new AMap.Marker({
								map: this.map,
								position: [this.routeInfo[0].lng, this.routeInfo[0].lat],
								icon: new AMap.Icon({
									image: mapCarRun,
									size: new AMap.Size(22, 28), //图标所处区域大小
									imageSize: new AMap.Size(22, 28) //图标大小
								}),
								autoRotation: true,
								offset: new AMap.Pixel(-26, -13),
								angle: 0,
							});
							this.map.add(this.marker)

							this.carWindow = new AMap.InfoWindow({
								offset: new AMap.Pixel(6, -25),
								content: ""
							});

							var pathPolyline = this.initializePaths(this.routeInfo);
							this.lineArr = []

							for (var i = 0; i < res.data.length; i++) {
								var lng = res.data[i].lng
								var lat = res.data[i].lat

								this.lineArr.push(
									[lng, lat]
								)
							}

							this.passedPolyline = new AMap.Polyline({
								map: this.map,
								path: this.lineArr,
								strokeColor: "#AF5", //线颜色
								strokeOpacity: 1, //线透明度
								strokeWeight: 6, //线宽
								strokeStyle: "solid" //线样式
							});

							this.map.add(this.passedPolyline)

							// 7.打开速度框
							this.carWindow.open(this.map, this.marker.getPosition());

							this.map.setFitView();



						}
					})
				}
			},
			selectNode(param) {

				if (param.type === 'car') {
					this.selectedNodes = param
					if (this.curDate) {
						getHistory({
							startTime: this.curDate + ' 00:00:00',
							endTime: this.curDate + ' 23:59:59',
							vehId: this.selectedNodes.id
						}).then(res => {
							console.log(res)
						})
					}

				}


			},

			initMap() {
				AMapLoader.load({
					key: "64a2876c96c2199296e28d0bdd64d43a", //此处填入我们注册账号后获取的Key
					version: "2.0", //指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: ['AMap.ToolBar', // 缩放按钮
						'AMap.Scale',
						'AMap.MoveAnimation',
						"AMap.Marker",
					], //需要使用的的插件列表，如比例尺'AMap.Scale'等
				}).then((AMap) => {
					this.map = new AMap.Map("amap", { //设置地图容器id
						viewMode: "3D", //是否为3D地图模式
						zoom: 5, //初始化地图级别
						center: [105.602725, 37.076636], //初始化地图中心点位置
						zoomEnable: true, // 地图是否可缩放，默认值为true
						dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
						doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
					});
					this.map.addControl(new AMap.ToolBar())
					this.map.addControl(new AMap.Scale())


				}).catch(e => {
					console.log(e);
				})
			},

			changeBottomFullScreen() {
				this.bottomdraw.fullBtn.num++;
				if (this.bottomdraw.fullBtn.num % 2 !== 0) {
					this.bottomdraw.style.height = '83vh'
					this.bottomdraw.btn.style.bottom = '84vh'
				} else {
					this.bottomdraw.style.height = '37vh'
					this.bottomdraw.btn.style.bottom = '38vh'
				}

			},
			changeBottom() {
				this.bottomdraw.fullBtn.num = 0
				if (this.bottomdraw.show) {
					this.bottomdraw.btn.icon = 'el-icon-top'
					this.bottomdraw.btn.style.bottom = '1vh'
					this.bottomdraw.show = false

				} else {
					this.bottomdraw.btn.style.bottom = '38vh'
					this.bottomdraw.btn.icon = 'el-icon-bottom'
					this.bottomdraw.style.height = '37vh'

					this.bottomdraw.show = true
				}
			},
			changeBtn() {

				if (this.drawer) {
					this.drawBtnIcon = 'el-icon-d-arrow-right'
					this.drawBtnStyle.left = '0vw'
					this.bottomdraw.style.left = '1vw'
					if (this.isCollapseLeftMenu) {
						this.bottomdraw.style.width = '85vw'
					} else {
						this.bottomdraw.style.width = '96vw'
					}
					this.videoFrame.left = 0
					this.drawer = false

				} else {
					this.drawBtnIcon = 'el-icon-d-arrow-left'
					this.drawBtnStyle.left = '20vw'
					this.bottomdraw.style.left = '21vw'
					if (this.isCollapseLeftMenu) {
						this.bottomdraw.style.width = '65vw'
					} else {
						this.bottomdraw.style.width = '76vw'
					}
					this.videoFrame.left = 20
					this.drawer = true
				}
			},
		},
		mounted() {
			this.initMap()
			var val = this.isCollapseLeftMenu
			if (val) {
				if (this.drawer) {
					this.bottomdraw.style.width = '65vw'
				} else {
					this.bottomdraw.style.width = '85vw'
				}

			} else {
				if (this.drawer) {
					this.bottomdraw.style.width = '76vw'
				} else {
					this.bottomdraw.style.width = '96vw'
				}
			}
		}
	}
</script>

<style lang="scss">
	.el-popover {
		padding: 0;
	}

	.jkzx-calendar {
		font-size: 12px;

		.el-calendar__header {
			padding: 0;
		}

		.el-calendar__body {
			padding: 0;
		}

		.el-calendar-day {
			padding: 0;
			height: 50px;
		}
	}
</style>